import { useState, useRef, useEffect } from "react";
import MessageActionCard from "./MessageActionCard";
import MessageBubble from "./MessageBubble";
import type { Contact } from "../../types";

interface MessagePanelProps {
  messages: Array<{
    id: string;
    senderId: string;
    content: string;
    timestamp: Date;
  }>;
  contacts: Record<string, Contact>;
  currentUserId: string;
}

export default function MessagePanel({
  messages,
  contacts,
  currentUserId,
}: MessagePanelProps) {
  const [activeMessageId, setActiveMessageId] = useState<string | null>(null);
  const [actionCardPosition, setActionCardPosition] = useState<{
    top: number;
    left?: number;
    right?: number;
  } | null>(null);
  const messageRefs = useRef<Record<string, HTMLDivElement | null>>({});

  const handleLongPress = (messageId: string) => {
    const messageElement = messageRefs.current[messageId];
    if (!messageElement) return;

    const rect = messageElement.getBoundingClientRect();
    const message = messages.find((m) => m.id === messageId);
    const isOwnMessage = message?.senderId === currentUserId;

    setActiveMessageId(messageId);

    if (isOwnMessage) {
      setActionCardPosition({
        top: rect.top + window.scrollY - 50,
        right: window.innerWidth - rect.right,
      });
    } else {
      setActionCardPosition({
        top: rect.top + window.scrollY - 50,
        left: rect.left,
      });
    }
  };

  const startPressTimer = (messageId: string) => {
    const timer = setTimeout(() => {
      handleLongPress(messageId);
    }, 500);

    messageRefs.current[messageId]?.setAttribute(
      "data-press-timer",
      timer.toString()
    );
  };

  const cancelPressTimer = (messageId: string) => {
    const timerString =
      messageRefs.current[messageId]?.getAttribute("data-press-timer");
    if (timerString) {
      clearTimeout(parseInt(timerString));
      messageRefs.current[messageId]?.removeAttribute("data-press-timer");
    }
  };

  const closeActionCard = () => {
    setActiveMessageId(null);
    setActionCardPosition(null);
  };

  useEffect(() => {
    const handleOutsideClick = (e: MouseEvent) => {
      if (
        activeMessageId &&
        !(e.target as HTMLElement).closest(".message-action-card")
      ) {
        closeActionCard();
      }
    };

    document.addEventListener("click", handleOutsideClick);
    return () => document.removeEventListener("click", handleOutsideClick);
  }, [activeMessageId]);

  return (
    <div className="relative">
      {messages.map((message) => {
        const sender = contacts[message.senderId];
        const isOwnMessage = sender.id === currentUserId;
        const avatarText = sender.name.charAt(0);

        return (
          <MessageBubble
            key={message.id}
            message={message}
            sender={sender}
            isOwnMessage={isOwnMessage}
            avatarText={avatarText}
            bubbleRef={(el) => {
              messageRefs.current[message.id] = el;
            }}
            onTouchStart={() => startPressTimer(message.id)}
            onTouchEnd={() => cancelPressTimer(message.id)}
            onTouchMove={() => cancelPressTimer(message.id)}
            onContextMenu={(e) => {
              e.preventDefault();
              handleLongPress(message.id);
            }}
          />
        );
      })}

      {activeMessageId && actionCardPosition && (
        <MessageActionCard
          messageId={activeMessageId}
          position={actionCardPosition}
          onClose={closeActionCard}
        />
      )}

      <div className="h-2"></div>
    </div>
  );
}
